﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QRCodeTools.Utils {
    
    public class CmdParamsHandlerMgr {
        class CmdEventHandler {
            public ISynchronizeInvoke InvokeThis { get; set; }
            public Action DelegateFn { get; set; }
        }

        private Dictionary<string, CmdEventHandler> CmdMapHandler = new Dictionary<string, CmdEventHandler>();

        public void RegCmd(Action delegateFn, ISynchronizeInvoke invokeThis, params string[] cmdParams) {
            if (cmdParams == null) return;
            var cmdEventHandler = new CmdEventHandler {
                InvokeThis= invokeThis,
                DelegateFn= delegateFn,
            };
            foreach (var pa in cmdParams) {
                if (pa == null) continue;
                CmdMapHandler[pa.Trim().ToLower()] = cmdEventHandler;
            }
        }

        /// <summary>
        /// 所有命令行参数直接触发处理器,并返回是否成功匹配并已经执行了
        /// 暂时只支持匹配到第一个处理器
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public bool TriggerHandlers(string[] args) {
            if (args == null || args.Length == 0) return false;
            foreach (var arg in args) {
                if (arg == null) continue;
                if(CmdMapHandler.TryGetValue(arg.Trim().ToLower() ,out var handler)){
                    handler.InvokeThis.Invoke(handler.DelegateFn, null);
                    return true;
                }
            }
            return false;
        }
    }
}
